package cloudnative.demo.labservice.controller;

import cloudnative.demo.labservice.mapper.DeviceMapper;
import cloudnative.demo.labservice.model.Device;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/device")
@Slf4j
public class DeviceController {

    @Autowired
    private DeviceMapper deviceMapper;

    private void jsonWrite(Object res, Object ret) {
        // This function can be used to process the response if needed
        // For simplicity, we'll directly return the result in this example
    }

    // 查询可用设备
    @GetMapping("/queryA")
    public List<Device> queryAvailableDevices() {
        log.info("-------------OK   //queryAD--------------------");
        return deviceMapper.queryAllDevices();
    }

    // 查询公共设备
    @GetMapping("/queryP")
    public List<Device> queryPublicDevices() {
        return deviceMapper.queryAllDevices();
    }

    // 查询所有设备
    @GetMapping("/queryAll")
    public List<Device> queryAllDevices() {
        return deviceMapper.queryAllDevices();
    }

    // 根据WorkerID、LaboratoryID查询设备
    @PostMapping("/queryM")
    public List<Device> queryDevicesByWorkerOrLab(@RequestBody Device device) {
        Long workerID = device.getWorkerID();
        Long laboratoryID = device.getLaboratoryID();
        List<Device> result = new ArrayList<>();
        if (workerID != null && laboratoryID == null) {
            return deviceMapper.findDevicesByWorkerId(workerID);
        } else if (laboratoryID != null && workerID == null) {
            result.add(deviceMapper.findDevicesByLaboratoryId(laboratoryID));
            return result;
        } else if (workerID != null && laboratoryID != null) {
            result.add(deviceMapper.findDevicesByWorkerAndLaboratoryId(laboratoryID,workerID));
            return result;
        } else {
            return deviceMapper.queryAllDevices();
        }
    }

    // 添加设备
    @PostMapping("/addD")
    public void addDevice(@RequestBody Device device) {
        deviceMapper.addDevice(device.getType(), device.getWorkerID(), device.getLaboratoryID());
    }

    // 删除设备
    @PostMapping("/deleteD")
    public void deleteDevice(@RequestBody Device device) {
        deviceMapper.deleteDevice(device.getDeviceID());
    }

    // 更新设备信息
    @PostMapping("/alterD")
    public void updateDevice(@RequestBody Device device) {
        deviceMapper.updateDevice(device.getDeviceID(), device.getType(), device.getWorkerID(), device.getLaboratoryID());
    }
}
